package com.cy.controller;

import com.cy.controller.ex.*;
import com.cy.entity.User;
import com.cy.service.IUserService;
import com.cy.service.ex.InsertException;
import com.cy.service.ex.UsernameDuplicatedException;
import com.cy.util.JsonResult;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 时间：2023/1/3
 */
@RestController
@RequestMapping("/users")
public class UserController extends BaseController{
    @Resource
    private IUserService userService;

    @RequestMapping("/reg")
    public JsonResult<Void> reg(User user){
        userService.reg(user);
        return new JsonResult<>(OK);
    }

    @RequestMapping("/login")
    public JsonResult<User> login(String username, String password, HttpSession httpSession){
        User data = userService.login(username, password);
        //向session中存储数据
        httpSession.setAttribute("uid",data.getUid());
        httpSession.setAttribute("username",data.getUsername());
        return new JsonResult<User>(OK,data);
    }

    @RequestMapping("/change_password")
    public JsonResult<Void> changePassword(String oldPassword,String newPassword,HttpSession httpSession){
        Integer uid = getuidFromSession(httpSession);
        String username =getUsernameFromSession(httpSession);
        userService.changePassword(uid,username,oldPassword,newPassword);
        return new JsonResult<>(OK);

    }

    /**
     * 根据用户id进行查找数据
     * @param httpSession
     * @return
     */
    @RequestMapping("/get_by_uid")
    public JsonResult<User> getByUid(HttpSession httpSession){
        User data = userService.getByUid(getuidFromSession(httpSession));
        return new JsonResult<>(OK,data);
    }

    /**
     * 修改用户数据
     * @param user
     * @param httpSession
     * @return
     */
    @RequestMapping("/change_info")
    public JsonResult<Void> changeInfo(User user,HttpSession httpSession){
        Integer uid =getuidFromSession(httpSession);
        String username = getUsernameFromSession(httpSession);
        userService.changeInfo(uid,username,user);
        return new JsonResult<>(OK);
    }

    //设置文件上传的最大值
    public static final int AVATAR_MAX_SIZE = 10*1024*1024;

    //设置文件上传的类型
    public static final List<String> AVATAR_TYPE = new ArrayList<>();
    static {
        AVATAR_TYPE.add("image/jpeg");
        AVATAR_TYPE.add("image/png");
        AVATAR_TYPE.add("image/bmp");
        AVATAR_TYPE.add("image/gif");
    }
    /**
     * MultipartFile接口时springMvc提供的一个接口，这个接口为我们包装了
     * 获取文件类型的数据（任何类型的file都可以接收）
     * @param httpSession
     * @param file
     * @return
     */
    @RequestMapping("/change_avatar")
    public JsonResult<String> changeAvatar(HttpSession httpSession, @RequestParam("file") MultipartFile file){
        //判断文件是否为null
        if(file.isEmpty()){
            throw new FileEmptyException("文件为空");
        }
        //判断文件大小是否超出限制
        if(file.getSize() > AVATAR_MAX_SIZE){
            throw new FileSizeException("文件超出限制");
        }
        //判断文件类型
        String contentType = file.getContentType();
        if(!AVATAR_TYPE.contains(contentType)){
            throw new FileTypeException("文件类型不支持");
        }

        //上传的文件.../upload/文件.png
        String parent = httpSession.getServletContext().getRealPath("upload");
        //File对象指向这个路径，FIle是否存在
        File dir = new File(parent);
        if(!dir.exists()){//检测目录是否存在
            dir.mkdirs();//创建当前目录
        }
        //获取到文件名称，UUID工具来将生成一个新的字符串作为文件名
        //例如avatar.png
        String originalFilename = file.getOriginalFilename();
        int index = originalFilename.lastIndexOf(".");
        String suffix = originalFilename.substring(index);
        String filename = UUID.randomUUID().toString().toUpperCase()+suffix;

        File dest = new File(dir,filename);//是一个空文件，在dir目录下创建filename文件
        //将参数file中数据写入到这个空文件
        try {
            file.transferTo(dest);//将file文件中的数据写入到dest文件中
        } catch (FileStateException e) {
            throw new FileStateException("文件状态异常");
        }catch (IOException e){
            throw new FileUploadIOException("文件读写异常");
        }

        Integer uid = getuidFromSession(httpSession);
        String username = getUsernameFromSession(httpSession);
        //返回头像的路径/upload/test.png
        String avatar = "/upload/" + filename;
        userService.changeAvatar(uid,avatar,username);
        //返回用户头像的路径给前端，将来用于头像的展示使用
        return new JsonResult<>(OK,avatar);
    }
}
